<script setup lang='ts'>
import { addCardAPI, editCardAPI, getCardDetailAPI } from '@/apis/card';
import type { AddCardData, EditCardData } from '@/types/card';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';

// 1. 新增车辆信息表单
const carInfoForm = ref<Partial<AddCardData>>({
  personName: '',
  phoneNumber: '',
  carNumber: '',
  carBrand: '',
})
// 校验规则
const carInfoFormRules = ref<FormRules<AddCardData>>({
  personName: [
    { required: true, message: '请输入车主姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
  ],
  phoneNumber: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  carNumber: [
    { required: true, message: '请输入车牌号码', trigger: 'blur' },
    { pattern: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/, message: '请输入正确的车牌号', trigger: 'blur' }
  ],
  carBrand: [
    { required: true, message: '请输入车辆品牌', trigger: 'blur' },
  ]
})

// 2. 新增缴费信息表单
const feeForm = ref<Partial<AddCardData>>({
  cardStartDate: '',
  cardEndDate: '',
  paymentAmount: '',
  paymentMethod: 'Alipay',
})
// 日期选择器数组
const dateArr = ref<string[]>([])
// 通过监听日期选择器数组，将数组中的值分别赋值给startDate和endDate
watch(dateArr, (newValue) => {
  if (newValue) {
    feeForm.value.cardStartDate = newValue[0]
    feeForm.value.cardEndDate = newValue[1]
  } else {
    feeForm.value.cardStartDate = ''
    feeForm.value.cardEndDate = ''
  }
})
// 校验规则
const feeFormRules = ref<FormRules<AddCardData>>({
  cardEndDate: [
    { required: true, message: '请选择有效日期', trigger: 'change' },
  ],
  paymentAmount: [
    { required: true, message: '请输入支付金额', trigger: 'blur' },
  ],
  paymentMethod: [
    { required: true, message: '请选择支付方式', trigger: 'blur' },
  ]
})

// 日期选择器禁用日期
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 1000 * 60 * 60 * 24
}

// 3. 提交表单
// 创建表单实例
const carInfoFormRef = ref<FormInstance>()
const feeFormRef = ref<FormInstance>()
// 获取路由实例
const router = useRouter()
// 提交表单
const onSubmit = async () => {
  try {
    await Promise.all([carInfoFormRef.value?.validate(), feeFormRef.value?.validate()])
    // 判断是编辑还是新增
    if (route.params.id) {
      await editCardAPI({
        ...carInfoForm.value,
        ...feeForm.value,
        ...editForm.value
      })
      ElMessage.success('编辑成功')
      router.back()
      return
    } else {
      await addCardAPI({
      ...carInfoForm.value,
      ...feeForm.value
    })
    ElMessage.success('新增成功')
    router.back()
    }
    
  } catch (error) {
    console.log(error)
  }
}

// 4. 重置表单
const onReset = () => {
  carInfoFormRef.value?.resetFields()
  feeFormRef.value?.resetFields()
  dateArr.value = []
}

// 5. 如果地址栏有id, 就进行编辑功能
const route = useRoute()
// 创建变量,提交编辑信息额外所需的缴费信息id和车辆信息id
const editForm = ref<Partial<EditCardData>>({
  carInfoId: undefined,
  rechargeId: undefined
})

onMounted(async () => {
  // 如果地址栏有id,根据id发送请求进行数据回显
  if (route.params.id) {
    const id = route.params.id
    const { data } = await getCardDetailAPI(id as string)
    carInfoForm.value = {
      personName: data.personName,
      phoneNumber: data.phoneNumber,
      carNumber: data.carNumber,
      carBrand: data.carBrand
    }
    feeForm.value = {
      cardStartDate: data.cardStartDate,
      cardEndDate: data.cardEndDate,
      paymentAmount: data.paymentAmount,
      paymentMethod: data.paymentMethod
    }
    dateArr.value = [data.cardStartDate, data.cardEndDate]
    editForm.value = {
      carInfoId: data.carInfoId,
      rechargeId: data.rechargeId
    }
  }
})
</script>

<template>
  <div>
    <el-page-header :content="$route.params.id ? '编辑月卡' : '增加月卡'" @back="$router.back()" />

    <!-- 车辆信息 -->
    <el-card>
      <template #header>
        车辆信息
      </template>

      <el-form :model="carInfoForm" :rules="carInfoFormRules" ref="carInfoFormRef">
        <el-form-item label="车主姓名：" prop="personName">
          <el-input placeholder="请输入车主姓名" v-model="carInfoForm.personName" />
        </el-form-item>
        <el-form-item label="联系方式：" prop="phoneNumber">
          <el-input placeholder="请输入联系方式" v-model="carInfoForm.phoneNumber" maxlength="11" />
        </el-form-item>
        <el-form-item label="车牌号码：" prop="carNumber">
          <el-input placeholder="请输入车牌号码" v-model="carInfoForm.carNumber" maxlength="8" />
        </el-form-item>
        <el-form-item label="车辆品牌：" prop="carBrand">
          <el-input placeholder="请输入车辆品牌" v-model="carInfoForm.carBrand" />
        </el-form-item>
      </el-form>
      {{ carInfoForm }}
    </el-card>

    <!-- 缴费信息 -->
    <el-card>
      <template #header>
        缴费信息
      </template>

      <el-form :model="feeForm" :rules="feeFormRules" ref="feeFormRef">
        <el-form-item label="有效日期：" prop="cardEndDate">
          <el-date-picker type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
            v-model="dateArr" value-format="YYYY-MM-DD" :validate-event="true" :disabled-date="disabledDate" />
        </el-form-item>
        <el-form-item label="支付金额：" prop="paymentAmount">
          <el-input placeholder="请输入金额" v-model="feeForm.paymentAmount" />
        </el-form-item>
        <el-form-item label="支付方式：" prop="paymentMethod">
          <el-select placeholder="请选择支付方式" v-model="feeForm.paymentMethod">
            <el-option
              v-for="item in [{ label: '支付宝', value: 'Alipay' }, { label: '微信', value: 'WeChat' }, { label: '线下', value: 'Cash' }]"
              :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      {{ feeForm }} {{ dateArr }}
    </el-card>

    <div class="button-container">
      <el-button @click="onReset">重置</el-button>
      <el-button type="primary" @click="onSubmit">提交</el-button>
      
    </div>
  </div>
</template>

<style scoped>
.el-card {
  width: 80%;
  margin: 0 auto;
  margin-top: 30px;
}

.el-form {
  padding: 15px 50px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.el-form-item {
  width: 420px;
}

.button-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;
  gap: 30px;
}
</style>
